/**
 * @desc 此为系统封装业务组件，业务相关，共全局业务代码使用，依赖系统基础组件
 * @author byte_su
 * @date 2018-02-25
 */
import React, {Component} from 'react';
import {StyleSheet, Image} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import Feather from 'react-native-vector-icons/Feather';
import RNCamera from '../components/RNCamera';
var ImagePicker  = require('react-native-image-picker');

import {
    Container, Header, Spinner, View, Right, Left, Body, Title,
    Content, Form, Item, Text, Input, ActionSheet, Toast, Label,
    List, Thumbnail, Button,
    ListItem, Root, Tab, Tabs
} from 'native-base';

function assign(...json) {
    return Object.assign({}, ...json);
}
import DatePicker from 'react-native-datepicker';// 日期选择组件
import {formatDate, get, jsonToQueryStr} from './common';// 日期选择组件

class MyDatePicker extends Component {
    constructor(props) {
        super(props)
        this.state = {
            date: formatDate(new Date),
            dateEnd: formatDate(new Date),
            dateStart: formatDate(new Date),
            endMin: formatDate(new Date)
        }
    }

    render() {
        const self = this;

        if (self.props.type == 'range') {
            return <View style={{flexDirection: 'row'}}>
                <DatePicker
                    style={self.props.style || {}}
                    mode="date"
                    date={this.state.dateStart}
                    placeholder={this.props.label || '选择日期'}
                    format="YYYY-MM-DD"
                    minDate={this.props.minDate || formatDate(new Date())}
                    maxDate="9999-12-12"
                    confirmBtnText="选择"
                    cancelBtnText="取消"
                    showIcon={false}
                    customStyles={{
                        dateIcon: {
                            position: 'absolute',
                            left: 0,
                            top: 4,
                            marginLeft: 0
                        },
                        dateInput: {
                            marginLeft: 0
                        }
                    }}
                    onDateChange={(date) => {
                        console.log(date);
                        this.setState({dateStart: date, endMin: date})
                    }}
                />
                <Text>-</Text>
                <DatePicker
                    style={{width: 100, paddingLeft: 0, marginLeft: 0}}
                    mode="date"
                    date={this.state.dateEnd}
                    placeholder={this.props.label || '选择日期'}
                    format="YYYY-MM-DD"
                    minDate={this.props.endMin || formatDate(new Date())}
                    maxDate="9999-12-12"
                    confirmBtnText="选择"
                    cancelBtnText="取消"
                    showIcon={false}
                    customStyles={{
                        dateIcon: {
                            position: 'absolute',
                            left: 0,
                            top: 4,
                            marginLeft: 0
                        },
                        dateInput: {
                            marginLeft: 0,
                            borderWidth: 0,
                        }
                    }}
                    onDateChange={(date) => {
                        console.log(date);
                        this.setState({dateEnd: date})
                    }}
                />
            </View>
        }
        return <View style={CSS.inlineCtner}>
            <Text style={CSS.lineLabel}>{this.props.label || '到期开始日期'}</Text>
            <DatePicker
                style={CSS.lineItem}
                mode="date"
                date={this.props.val || this.state.date}
                placeholder={this.props.label || '选择日期'}
                format="YYYY-MM-DD"
                minDate={this.props.minDate || formatDate(new Date())}
                maxDate="9999-12-12"
                confirmBtnText="选择"
                cancelBtnText="取消"
                showIcon={false}
                customStyles={{
                    dateIcon: {
                        position: 'absolute',
                        left: 0,
                        top: 4,
                        marginLeft: 0
                    },
                    dateInput: {
                        marginLeft: 0,
                        width: 100,
                        height: 50,
                        // justifyContent: 'flex-end',
                        alignItems: 'flex-end',
                        fontSize: 20,
                        marginTop: 7,
                        fontSize: 30,
                        borderWidth: 0, paddingRight: 5
                    }
                }}
                onDateChange={(date) => {
                    this.setState({date: date});
                    self.props.change && self.props.change(date)
                }}
            />
        </View>
    }

}
const CSS = StyleSheet.create({
    inlineCtner: {flexDirection: 'row', height: 50, borderWidth: 0, flex: 1},
    lineItem: {
        flex: 1, borderWidth: 0, width: 100,
        height: 50, fontSize: 20,
    },
    lineLabel: {color: '#6b6b6b', borderWidth: 0, alignSelf: 'center'},
});
/**
 *  表单组件
 */
class Fom extends Component {
    constructor(props) {
        super(props);
        this.state = {
            min: formatDate(new Date())
        };
    }

    render() {
        const self = this;
        return (
            <Form {...this.props}>
                {
                    self.props.data.length ? self.props.data.map((item, index) => {
                        if (item.type == 'range') { // 日期范围选择框
                            return <Item key={index}>
                                <MyDatePicker
                                    type="range"
                                    onChange={(val) => {
                                        val && self.setState(val)
                                    }}
                                    min={self.state.min}
                                    label="选择日期"
                                />
                            </Item>;
                        } else if (item.type == 'date') { //日期选择框
                            return <Item key={index}>
                                <MyDatePicker
                                    {...Object.assign({}, item, {
                                        change: () => {
                                        }
                                    })}
                                    change={(date) => {
                                        var t = {};
                                        t[item.name] = date;
                                        self.setState(t);
                                    }}
                                />
                            </Item>;
                        } else {
                            if (index == (self.props.data.length - 1)) {
                                <Item
                                    {...(item.formItemType == 'inline' ? {} : {floatingLabel: true})}
                                    style={item.Itemstyle || {paddingLeft: 2}}
                                    key={index}>
                                    <Label>{item.label}</Label>
                                    <Input
                                        secureTextEntry={item.password ? true : false}
                                        onChangeText={(text) => {
                                            var t = {};
                                            t[item.name] = text;
                                            self.setState(t)
                                        }}
                                        style={Object.assign({alignItems: 'flex-end',}, item.style || {})}
                                        editable={item.editable || false}
                                        value={((self.state[item.name] + "") != 'undefined') ? self.state[item.name] : (item.val || '')}
                                        placeholder={item.placehoder || ''}
                                        name={item.name}
                                        ref={item.name}
                                    />
                                    {item.sibling}
                                    <Icon name='md-checkmark-circle-outline'/>
                                </Item>
                            }

                            return <Item
                                last
                                {...(item.formItemType == 'inline' ? {} : {floatingLabel: true})}
                                style={item.Itemstyle || {paddingLeft: 2}}
                                key={index}>
                                {/*<Label>{item.label}</Label>*/}
                                <Input
                                    secureTextEntry={item.password ? true : false}
                                    placeholder={item.placehoder || ''}
                                    onChangeText={(text) => {
                                        var t = {};
                                        t[item.name] = text;
                                        self.setState(t)
                                    }}
                                    style={Object.assign({
                                        alignItems: 'flex-end',
                                        alignItems: 'flex-end',
                                        justifyContent: 'flex-end'
                                    }, item.style || {})}
                                    value={((self.state[item.name] + "") != 'undefined') ? self.state[item.name] : (item.val || '')}
                                    name={item.name}
                                    ref={item.name}
                                />
                                {item.sibling}
                            </Item>
                        }
                    }) : <Spinner/>
                }
            </Form>
        );
    }
}
/**
 * ListView 列表组件
 */
class ListView extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: true, // 正在加载中
            noData: false,//没有更多数据了,
            data: [],// 列表数据
            page: {},
            firstMount: true,// 首次挂载
        };
        this.queryData = this.queryData.bind(this);
    }

    componentWillReceiveProps(nextProps) {

    }

    shouldComponentUpdate(nextProps, nextState) { // 自组件是否应该变化
        console.log(this.props.filter);
        const self = this;
        if (self.state.data.length == 0) { // 首次挂载，允许变更
            return true;
        }
        return true;
        // if (nextProps.filter == this.props.filter) { // 父、子组件的fitlerData相同时，无需更新
        //     return false;
        // }
    }

    /**
     *  组件加载...
     */
    componentDidMount() {
        const self = this;
        self.queryData({})
    }

    /**
     *  查询请求
     * @param filter
     */
    queryData(filter) {
        const self = this;
        get(self.props.url + '?' + jsonToQueryStr(filter || {}))
            .then((res) => {
                self.props.setSum && self.props.setSum({total: res.page.total});
                self.setState({
                    data: res.list ? [...self.state.data, ...res.list] : self.statte.data,
                    noData: res.list.length == 15 ? false : true,
                    loading: false,
                    page: res.page || {}
                });
            });
    }

    render() {
        const self = this;
        let {data} = this.state;
        return (
            <Content>
                <List>
                    {
                        data.map((item, index) => (this.props.renderItem ? this.props.renderItem(item, index) :
                            <Text>No Data</Text>))
                    }
                </List>
                {self.state.loading ? <Loading/> : (self.state.noData ?
                    <NoMoreData/> :
                    <Button
                        small
                        block
                        transparent
                        onPress={() => {
                            self.queryData({page: self.state.page.page + 1})
                        }}
                        style={{margin: 5, flex: 1, flexDirection: 'row'}}
                    >
                        <Text>加载更多</Text>
                    </Button>)}
            </Content>
        );
    }
}

/**
 *  提示消息
 * @param msg
 * @param position
 */
function tips(msg, position, type) {
    Toast.show({
        text: msg || 'Wrong password!',
        position: position || 'bottom', //top, bottom
        type: type || 'danger',
        buttonText: ''
    })
}
/**
 * 错误提示
 * @param msg
 */
function fnFail(msg) {
    tips(msg, 'top');
}
/**
 * 成功提示
 * @param msg
 */
function fnSuccess(msg) {
    tips(msg, 'top', 'success');
}
/**
 *  表单验证
 * @param list
 * @param data
 * @returns {boolean}
 */
function validateForm(list, data) {
    var flag = true;
    for (var i = 0; i < list.length; i++) {
        var item = list[i];
        if (item.required) {
            if (data[item.name] && data[item.name].length) {

            } else {
                return fnFail(item.error || ('请输入' + item.label));
                flag = false;
            }

        }
    }
    return flag;
}
/**
 * 获取修改后、修改前的合并对象，修改后数据自动覆盖修改前数据
 * @param list
 * @param data
 * @returns {*}
 */
function getMergeFormData(list, data) {
    list.map(item => {
        if (!data[item.name]) data[item.name] = item.val || '';
    });
    return data;
}
/**
 * 按钮组件
 * @param props
 * @returns {XML}
 * @constructor
 */
const Btn = (props) => {
    const self = this;
    return <Button
        onPress={(e) => {
            console.log('d')
        }}
        bordered danger>
        <Text> 提 交 </Text>
    </Button>

};
/**
 * 加载提示组件
 * @param props
 * @returns {XML}
 * @constructor
 */
const Loading = (props) => {
    return <Spinner/>
};
const DataTips = (props) => {
    return <View
        style={{
            flex: 1,
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'center',
        }}
    >
        <Text style={{
            fontSize: 30,
            color: 'green',
        }}>{props.children}</Text>
    </View>
}
/**
 *  没有更多数据提示组件
 * @param props
 * @returns {XML}
 * @constructor
 */
const NoMoreData = (props) => {
    return <View style={{
        justifyContent: 'center',
        flexDirection: 'row',
        alignItems: 'center',
        paddingTop: 20,
        paddingBottom: 20
    }}>
        <Text
            style={{color: '#676767', fontSize: 12}}
        >没有更多数据了</Text>
    </View>
};

function auctionSheet(title, BUTTONS, CANCEL_INDEX, cb, DESTRUCTIVE_INDEX) {
    ActionSheet.show(
        assign({
            options: BUTTONS,
            cancelButtonIndex: CANCEL_INDEX || (BUTTONS.length - 1),
            title: title
        }, DESTRUCTIVE_INDEX ? {destructiveButtonIndex: DESTRUCTIVE_INDEX,} : {}),
        buttonIndex => {
            console.log(BUTTONS[buttonIndex]);
            cb && cb(buttonIndex)
        }
    )
}


import Drawer from 'react-native-drawer';//抽屉功能 https://github.com/root-two/react-native-drawer#demo

export * from './common';
export {
    Fom,
    Root,
    RNCamera,
    Loading,
    StyleSheet, Header,
    Text,
    Image,
    Right,
    Left, Title, Body, Button,
    DataTips,
    Drawer,
    Icon,
    Feather,
    ListView,
    NoMoreData,
    DatePicker,
    MyDatePicker,
    validateForm,
    getMergeFormData,
    auctionSheet,
    fnFail,
    fnSuccess,
    ImagePicker
};
